package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("server start!");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true){
            //1、首先接收客户端的连接，才能进行通信
            Socket socket = serverSocket.accept();
            //2、通过下面的方法来处理 整个连接过程
//            Thread thread = new Thread(() -> {
//                try {
//                    processConnection(socket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            thread.start();
            executorService.submit(() ->{
                try {
                    processConnection(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

        }
    }

    private void processConnection(Socket socket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n", socket.getInetAddress(), socket.getPort());
        try (InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true){//处理多次请求
                //1、读取数据
                if(!scanner.hasNext()){
                    System.out.printf("[%s ,%d]客户端下线\n",socket.getInetAddress().toString(),socket.getPort());
                    break;
                }
                String request = scanner.next();
                //2、根据请求计算响应
                String response = process(request);
                //3、把请求返回给客户端
                printWriter.println(response);
                printWriter.flush();//冲刷缓冲区
                //4、打印日志
                System.out.printf("[%s ,%d], request: %s, response: %s\n",
                        socket.getInetAddress().toString(),socket.getPort(),request,response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            socket.close();//关闭socket文件
        }

    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
